(function(){
var i_cnt=0;
var i_jslist=[


	/*
	Usage :
	We trying to preload the script.js file after the html loading.
	which improve the loading speed when there is too many/big script file to load.
	you can define which file load first, and need to wait until the lower level script was loaded.
	
	Fill in the [object] in array as format
	{level: #Number, path : #Address}
	desc :
		level = the file level, LOWER means it will loaded first
		path = the file path
		
	Usage 2:
	After jslist loaded compelete it will fire the custom "preload" event.
	you can catch it by
		$(document).bind('preload',function(){	}
	*/
	{level:0, path : './js/jquery.cf.utils.js'},
	{level:0, path : './js/jquery.cookie.js'},
	{level:1, path : './js/script.js'}
];




function init_check(){
	i_jslist.sort(function(a,b){return a.level-b.level;}); // sort i_jslist by level
	/**** Alert for jslist ****
	var tmp=new Array();
	for(var i=0; i<i_jslist.length;i++) tmp.push("level:"+ i_jslist[i].level +",loaded:"+i_jslist[i].loaded +", path:"+ i_jslist[i].path +"\n");
	alert(tmp);
	//*************************/
	if(i_jslist.length>0) loadNext();
}//fn

function loadNext(){
	var _levelFinish=true;						// default is true, if everyone is onload.
	var _AllFinish=true;
	for(var i=0; i<i_jslist.length;i++){
		if( i_jslist[i].level == i_cnt){
			if( i_jslist[i].loaded==undefined ){ _levelFinish=false; launch(i) }
			else if( i_jslist[i].loaded=="loading" ){ _levelFinish=false;	}// we waiting someone, who fire the last call.
			else if( i_jslist[i].loaded=="fail" ) {}	// Error
			// if "success", we do nothing and the _levelFinish will be true.
		}//if
		if( !(i_jslist[i].loaded=="success" || i_jslist[i].loaded=="fail") ) _AllFinish=false; 
	}//for
	if( _levelFinish ){
		i_cnt++;
		if( _AllFinish){
			$(document).trigger('preload');	// preload everything in list finish
			delete i_cnt;
			delete this;
		}else{
			loadNext();						// this level is finish, try next level.
		}//if
	};
}//fn

function launch(_no){
	$.ajax({
		type: "GET",
		cache: true,				// we calling a script, which we want to cache it.
		url: i_jslist[_no].path,
		dataType: "script",
		beforeSend: function(){		// Handle the beforeSend event
			i_jslist[_no].loaded="loading";
		},
		success:function(_script, _status, _XHR){
			i_jslist[_no].loaded="success";
			loadNext();
			// try{ $.debug("Level "+i_jslist[_no].level+", "+ i_jslist[_no].path + " loaded. "); }catch(e){}	// DEBUG
		},
		error: function(_xhr, _status){
			i_jslist[_no].loaded="fail";
		}
	});
}//fn

init_check();	// start to preload
})();